import tkinter as tk
import tkinter.ttk as ttk
import math
from tkinter import filedialog
from PIL import Image, ImageTk
import time

_app_version_num = 1

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.count = 0
        self.show_label_text = False
        self.width = 960
        self.height = 720
        self.color = '#87CEEB'
        self.log_text = {}
    
    def load_basic_config(self):
        self.iconbitmap('charge.ico')
        self.title(f'充电小助手 V{round(math.e, _app_version_num)}')
        self.geometry(f'{self.width}x{self.height}')
        self.configure(background=self.color) 
        self.resizable(False, False)
    
    def create_starup_page(self):
        # 首页
        self.frame_image = tk.Frame(self)
        self.frame_image.pack(side='top', expand=True)

        self.image = tk.PhotoImage(file='charge_bg_2.png')
        self.label = tk.Label(self.frame_image, image=self.image)
        self.label.pack()

        ###
        # 设备配置文件导入
        self.frame_cfg_file = tk.Frame(self, background=self.color)
        self.frame_cfg_file.pack(side='top', expand=True)
        self.label = tk.Label(self.frame_cfg_file, text="设备环境配置文件", background=self.color)
        self.label.pack(side='left', anchor='center')
        self.env_file_path_entry = tk.Entry(self.frame_cfg_file, width=60)
        self.env_file_path_entry.pack(side='left', anchor='center', padx=5) # , expand=True
        self.choose_env_file_button = tk.Button(self.frame_cfg_file, text='浏览', command=self.open_file)
        self.choose_env_file_button.pack(side='left', anchor='center')
        self.export_env_file_button = tk.Button(self.frame_cfg_file, text='导入')
        self.export_env_file_button.pack(side='left', anchor='center', padx=5)

        ###
        # self.frframe_for_pack3 = tk.Frame(self)
        # self.frframe_for_pack3.pack(side='top', expand=True)

        ### 
        # IP列表选择
        self.frame_choose_env = tk.Frame(self, background=self.color)
        self.frame_choose_env.pack(side='top', expand=True)
        self.label_device_ip = tk.Label(self.frame_choose_env, text="设备IP列表", background=self.color)
        self.label_device_ip.pack(side='left', anchor='center')
        self.selected_option = tk.StringVar()
        self.device_option_list = ttk.Combobox(self.frame_choose_env, textvariable=self.selected_option, values=())
        # self.device_option_list.current(0)
        self.device_option_list.configure(width=60)
        self.device_option_list.pack(side='left', anchor='center', padx=5)
        self.device_connection_button = tk.Button(self.frame_choose_env, text='连接', command=self.connect)
        self.device_connection_button.pack(side='left', anchor='center', padx=5)

        ### 
        self.frame_for_pack = tk.Frame(self)
        self.frame_for_pack.pack(side='top', expand=True)
        self.frame_for_pack2 = tk.Frame(self)
        self.frame_for_pack2.pack(side='top', expand=True)
    
    def run(self):
        self.create_starup_page()
        
    def open_file(self):
        file_path = filedialog.askopenfilename()
        self.env_file_path_entry.insert(0, str(file_path))
    
    def connect(self):
        """连接到设备
        """
        # print(f"======== will connect to: {self.selected_option.get()}")
        self.hidden_startup_page()

        self.notebook = ttk.Notebook(self)
        self.notebook.pack(expand=True, fill='both')

        # 添加选项卡
        self.frame_tab1 = tk.Frame(self.notebook, background=self.color)
        self.tab1 = self.notebook.add(self.frame_tab1, text='基本信息')
        
        self.frame_tab2 = tk.Frame(self.notebook) # , background=self.color
        self.tab2 = self.notebook.add(self.frame_tab2, text='充电枪1')

        self.frame_tab3= tk.Frame(self.notebook) # , background=self.color
        self.tab3 = self.notebook.add(self.frame_tab3, text='充电枪2')

        self.create_basic_tab_content(self.frame_tab1)
        self.create_tab(self.frame_tab2, 1)
        self.create_tab(self.frame_tab3, 2)
    
    def create_basic_tab_content(self, frame):
        """获取基本信息页面
        """
        # 根据枪的个数，此处假设是2
        gun_num = 2
        info = [
            "充电主机信息:",
            "   [IP地址] 192.168.0.10",
            "   [配电检测板信息] 串口服务器地址: 192.168.0.11:10038; 通信地址: 36",
            "   [投切板地址信息] 串口服务器地址: 192.168.0.11:10039; 通信地址: 2",
            "   [ACDC地址信息] 串口服务器地址: 192.168.0.12:20001; 通信地址: 17",
            "   [DCDC地址信息] 串口服务器地址: 192.168.0.12:20002; 通信地址: 13",
            "充电控制器1信息:",
            "   [IP地址] 192.168.11.10",
            "   [车BMS地址信息] 串口服务器地址: 192.168.0.12:20003; 通信地址: 1",
            "   [直流电表地址] 串口服务器地址: 192.168.0.12:20003; 通信地址: 80",
            "   [温控板地址] 串口服务器地址: 192.168.0.12:20004; 通信地址: 120",
            "充电控制器2信息:",
            "   [IP地址] 192.168.11.11",
            "   [车BMS地址信息] 串口服务器地址: 192.168.0.12:20003; 通信地址: 1",
            "   [直流电表地址] 串口服务器地址: 192.168.0.12:20003; 通信地址: 80",
        ]
        text = "\n".join(info)
        tab_label = tk.Label(frame, text=text, font='Times 16', relief='groove', justify='left', background=self.color)
        tab_label.pack(side='top', anchor='n') #   , fill='both', padx=100, pady=100

        buttoun_exit = tk.Button(frame, text='退出', width=15, height=3, background='lightgray', font='Times 14 bold', relief='raised')
        buttoun_exit.pack(anchor='center')
    
    def create_tab(self, frame: tk.Frame, gun_no: int):
        frame.columnconfigure(0, weight=1)
        frame.columnconfigure(1, weight=1)
        frame.rowconfigure(0, weight=1)
        frame.rowconfigure(1, weight=1)

        frame11 = tk.Frame(frame, background='lightyellow')
        frame12 = tk.Frame(frame, background='lightblue')
        frame21 = tk.Frame(frame, background='lightblue')
        frame22 = tk.Frame(frame, background='lightyellow')

        frame11.grid(row=0, column=0, sticky='nsew')
        frame12.grid(row=0, column=1, sticky='nsew')
        frame21.grid(row=1, column=0, sticky='nsew')
        frame22.grid(row=1, column=1, sticky='nsew')

        label1 = tk.Label(frame11, text='采集区域', relief='raised')
        # label1.grid(row=0, column=0, columnspan=2, sticky='ew')
        label1.pack(fill='both')
        # 采集区域的信息
        label11_gun_status = tk.Label(frame11, text="充电枪状态" + " : " + "待机已插枪")
        label11_gun_status.pack(side='top', anchor='center', pady=10)
        label11_dcmeter_volt = tk.Label(frame11, text="充电电压" + " : " + "600V")
        label11_dcmeter_volt.pack(side='top', anchor='center')
        label11_dcmeter_curr = tk.Label(frame11, text="充电电流" + " : " + "240A")
        label11_dcmeter_curr.pack(side='top', anchor='center', pady=10)
        # label11_gun_status_value = tk.Label(frame11, text="", background='lightblue', relief='sunken')
        # label11_gun_status_value.grid(row=1, column=1, sticky='ew')
        # label11_gun_status_value.pack(side='left', fill='x')


        label2 = tk.Label(frame12, text='设置区域', relief='raised')
        label2.pack(fill='both')

        labe21 = tk.Label(frame21, text='控制区域', relief='raised')
        labe21.pack(fill='both')
        buttoun_startup_monitor = tk.Button(frame21, text='启动监测', width=15, height=3, background='lightgreen', font='Times 14 bold', relief='raised')
        buttoun_startup_monitor.pack(anchor='center')
        buttoun_stop_monitor = tk.Button(frame21, text='停止监测', width=15, height=3, background='lightgray', font='Times 14 bold', relief='raised', state=tk.DISABLED)
        buttoun_stop_monitor.pack(anchor='center', pady=5)

        buttoun_stop_charge = tk.Button(frame21, text='近端停止充电', width=15, height=3, background='lightgray', font='Times 14 bold', relief='raised', state=tk.DISABLED)
        buttoun_stop_charge.pack(side='bottom')
        buttoun_start_charge = tk.Button(frame21, text='近端启动充电', width=15, height=3, background='lightgreen', font='Times 14 bold', relief='raised', state=tk.DISABLED)
        buttoun_start_charge.pack(side='bottom', pady=5)
        

        labe22 = tk.Label(frame22, text='日志信息', relief='raised')
        labe22.pack(fill='both')
        self.log_text[gun_no] = tk.Text(frame22, state=tk.DISABLED)
        self.log_text[gun_no].pack(fill='both', expand=True)

    def hidden_startup_page(self):
        self.frame_image.pack_forget()
        self.frame_cfg_file.pack_forget()
        self.frame_choose_env.pack_forget()
        self.frame_for_pack.pack_forget()
        self.frame_for_pack2.pack_forget()
    
    def update_log(self, gun_no, log):
        if gun_no not in self.log_text.keys():
            return
        self.log_text[gun_no].configure(state=tk.NORMAL)
        self.log_text[gun_no].insert(tk.END, f'{time.strftime("%Y-%m-%d %H:%M:%S")} : {log}' + '\n')
        self.log_text[gun_no].configure(state=tk.DISABLED)
        self.log_text[gun_no].see(tk.END)
    
def lopp_call( app):
        log = 'this is test log'
        app.update_log(1, log)
        app.after(1000, lambda: lopp_call(app))

if __name__ == '__main__':
    app = App()
    app.load_basic_config()
    app.run()
    
    app.after(1000, lambda: lopp_call(app))
    app.mainloop()